package com.ls.lserp.modules.order.web;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.order.entity.BigcargoStyle;
import com.ls.lserp.modules.order.entity.SampleEmployeeEntity;
import com.ls.lserp.modules.order.entity.SampleType;
import com.ls.lserp.modules.order.entity.SpecimenDemand;
import com.ls.lserp.modules.order.entity.UploadFileData;
import com.ls.lserp.modules.order.service.BigcargoStyleService;
import com.ls.lserp.modules.order.service.SpecimenDemandService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/specimen/demand")
public class SpecimenDemandController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private SpecimenDemandService specimenDemandService;
	// 保存 编辑 删除 方法
	@Autowired
	private BigcargoStyleService bigcargoStyleService;
	@Autowired
	Configuration freemarkerConfiguration;
	String otherImageFlgTemp = "";

	// @ModelAttribute
	// public SpecimenDemand get(@RequestParam(required = false) String id) {
	//
	// // 判断id是否为空
	// if (StringUtils.isNotBlank(id)) {
	//
	// // 执行查询语句 查询基本信息
	// return specimenDemandService.get(Long.parseLong(id));
	// } else {
	//
	// // 若为空，实例化
	// return new SpecimenDemand();
	// }
	// }

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("specimen:demand:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 返回页面地址
		return "modules/order/specimenDemand";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param specimenDemand
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws ResourceException
	 */
	@RequiresPermissions("specimen:demand:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(SpecimenDemand specimenDemand, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "specimenDemand");

		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&sampleRequestNo=");
		searchParam.append(specimenDemand.getSampleRequestNo());
		searchParam.append("&styleNo=");
		searchParam.append(specimenDemand.getStyleNo());
		searchParam.append("&styleNameCn=");
		searchParam.append(specimenDemand.getStyleNameCn());
		searchParam.append("&ognizationName=");
		searchParam.append(specimenDemand.getOgnizationName());
		searchParam.append("&dateFrom=");
		searchParam.append(specimenDemand.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(specimenDemand.getDateTo());
		// searchParam.append("&userId=");
		// searchParam.append(specimenDemand.getUserId());
		searchParam.append("&tabPageStatus=");
		searchParam.append(specimenDemand.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());

		// 查询一览页面数据
		Page<SpecimenDemand> page = specimenDemandService.findList(new Page<SpecimenDemand>(request, response),
				specimenDemand);
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		try {
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("specimenDemands", page.getList());
			map.put("pageNo", page.getPageNo());
			map.put("pageSize", page.getPageSize());
			strHtml = FreeMarkerTemplateUtils
					.processTemplateIntoString(freemarkerConfiguration.getTemplate("specimenDemand.ftl"), map);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
		}

		listMap.put("specimenDemand", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * @Title: 新建画面迁移
	 * @Description: 新建画面迁移
	 * @param model
	 * @return url
	 * @throws ResourceException
	 */
	@RequiresPermissions("specimen:demand:edit")
	@RequestMapping(value = { "createStyle" })
	public String createStyle(BigcargoStyle bigcargoStyle, Model model) {
		long samplerequestId = bigcargoStyle.getSampleRequestId();
		String otherImageFlg = bigcargoStyle.getOtherImageFlg();
		bigcargoStyle.setPhaseCd(ResourcesUtil.getConfig("audit_phase_specimen"));
		// 创建人员
		model.addAttribute("user", UserUtils.getUser());
		// 物料部位
		List<Dict> materialPlacement = DictUtils.getDictList(ResourcesUtil.getConfig("material_placement"));
		List<UploadFile> myStyleFileList = null;
		// 样品类别
		List<Dict> sampleType = DictUtils.getDictList(ResourcesUtil.getConfig("sample_type"));
		model.addAttribute("sampleType", sampleType);
		// 获取图片关联ID
		String styleOptionId = bigcargoStyleService.getstyleOptionId(bigcargoStyle);
		// 获取所有图片信息
		myStyleFileList = bigcargoStyleService.getAllFile(styleOptionId);
		// 查看画面进去
		if (bigcargoStyle.getStyleID() > 0) {
			if ("".equals(bigcargoStyle.getUploadFile())) {
				bigcargoStyle.setUploadFile("/fragsmart-erp/static/images/pic-none.jpg");
			}
			BigcargoStyle bigcargoStyleTemp = bigcargoStyleService.selectSpecimenDemandStyle(bigcargoStyle);
			bigcargoStyleTemp.setSampleRequestId(samplerequestId);
			User sampleMakeUser = UserUtils.get(bigcargoStyleTemp.getSampleMakeId());
			User sampleSamUser = UserUtils.get(bigcargoStyleTemp.getSampleSamId());
			if (sampleMakeUser != null) {
				bigcargoStyleTemp.setSampleMakeName(sampleMakeUser.getFirstName() + sampleMakeUser.getLastName());
			}
			if (sampleSamUser != null) {
				bigcargoStyleTemp.setSampleSamName(sampleSamUser.getFirstName() + sampleSamUser.getLastName());
			}
			BigcargoStyle objBigStyleList = bigcargoStyleService.styleSizeList(bigcargoStyle);
			model.addAttribute("StyleOptionList",
					objBigStyleList.getBigcargoStyleFitProperty().getBigcargoStyleFitProperty());
			model.addAttribute("styleFit", objBigStyleList.getSampleTypeDataList().getStyleFit().getStyleFitList());
			model.addAttribute("styleSizeList", objBigStyleList.getSampleTypeDataList().getSampleTypeList());
			model.addAttribute("cgMaterialList", objBigStyleList.getChangeMaterial().getCgMatList());
			model.addAttribute("feedBackList", objBigStyleList.getStyleFeedBack().getStyleFeedBackList());
			model.addAttribute("imageList", objBigStyleList.getUploadFileData().getAllDataList());
			model.addAttribute("productionList", objBigStyleList.getProductionEntity().getProductionList());
			model.addAttribute("operatingList", objBigStyleList.getProduceParameter().getProduceParameterList());
			model.addAttribute("bigcargoStyleTempID", bigcargoStyleTemp);
			if ("specimenProduction".equals(otherImageFlg)) {
				model.addAttribute("difKbn", "3");
			} else if ("specimen".equals(otherImageFlg)) {
				model.addAttribute("difKbn", "1");
			}
			otherImageFlgTemp = otherImageFlg;
			// 新建按钮进去
		} else {
			model.addAttribute("difKbn", "2");
		}

		model.addAttribute("myStyleFileList", myStyleFileList);
		model.addAttribute("materialPlacement", materialPlacement);
		return "modules/order/specimenDemandCreate";
	}

	/**
	 * @Title: 参考款式检索
	 * @Description: 检索
	 * @param bigcargoStyle
	 * @param model
	 * @param request
	 * @param response
	 * @return list
	 */
	@RequiresPermissions("specimen:demand:edit")
	@RequestMapping(value = "selectDemandStyle")
	@ResponseBody
	public String selectDemandStyle(BigcargoStyle bigcargoStyle, Model model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		BigcargoStyle bigStyleObj = null;
		if (bigcargoStyle.getSampleRequestId() != 0) {
			bigcargoStyle.setPhaseCd(ResourcesUtil.getConfig("audit_phase_specimen"));
		} else {
			bigcargoStyle.setPhaseCd(ResourcesUtil.getConfig("audit_phase_style"));
		}
		String allFlie = bigcargoStyle.getStyleFile();
		bigStyleObj = bigcargoStyleService.styleSizeList(bigcargoStyle);
		// 款式尺码list生成
		List<SampleType> styleSizeList = bigStyleObj.getSampleTypeDataList().getSampleTypeList();
		// 款式图片list生成
		List<UploadFileData> imageListTemp = bigStyleObj.getUploadFileData().getAllDataList();
		String urlTemp = "";
		String imageHtml = "";
		String fitSizeHtml = "";
		String changeMaterialHtml = "";
		String feedBackHtml = "";
		String uploadFileHtml = "";
		String uploadFileDataHtml = "";
		// 生成hidden用url字符串
		for (int i = 0; i < imageListTemp.size(); i++) {
			if (imageListTemp.get(i) != null && imageListTemp.get(i).getFileKbn() == 0) {
				urlTemp += "|" + (imageListTemp.get(i).getFilePath() + imageListTemp.get(i).getUploadFileName());
			}
		}
		listMap.put("urlTemp", urlTemp);
		map.put("imageList", imageListTemp);
		map.put("allFlie", allFlie);
		map.put("user", UserUtils.getUser().getFirstName() + UserUtils.getUser().getLastName());
		map.put("otherImageFlg", otherImageFlgTemp);
		// 生成款式图片的HTML
		imageHtml = createHtml(map, "imageUrlList.ftl");
		// 生成样板文件画面的HTML
		uploadFileHtml = createHtml(map, "upLoadFileList.ftl");
		// 生成资料文件画面的HTML
		uploadFileDataHtml = createHtml(map, "upLoadFileListData.ftl");
		// 生成规格尺寸模板
		map = new HashMap<String, Object>();
		map.put("StyleOptionList", bigStyleObj.getBigcargoStyleFitProperty().getBigcargoStyleFitProperty());
		map.put("springMacroRequestContext", new RequestContext(request));
		String sizeModelHtml = "";
		sizeModelHtml = createHtml(map, "sizeFitProperty2.ftl");
		listMap.put("sizeModeHtml", sizeModelHtml);
		// 面辅料数据取得
		map = new HashMap<String, Object>();
		map.put("cgMaterialList", bigStyleObj.getChangeMaterial().getCgMatList());
		List<Dict> materialPlacement = DictUtils.getDictList(ResourcesUtil.getConfig("material_placement"));
		map.put("itemList", materialPlacement);
		map.put("springMacroRequestContext", new RequestContext(request));
		map.put("otherImageFlg", otherImageFlgTemp);
		// 生成面辅料画面的HTML
		changeMaterialHtml = createHtml(map, "specimenChangeStyleMaterial.ftl");
		// 意见要求数据取得
		map = new HashMap<String, Object>();
		map.put("feedBackList", bigStyleObj.getStyleFeedBack().getStyleFeedBackList());
		map.put("user", UserUtils.getUser().getFirstName() + UserUtils.getUser().getLastName());
		// 意见要求画面的HTML
		feedBackHtml = createHtml(map, "opinionList.ftl");
		// ajax前后台交互用list
		// listMap.put("fitSizeHtml", fitSizeHtml);
		listMap.put("imageListHtml", imageHtml);
		listMap.put("uploadFileHtml", uploadFileHtml);
		listMap.put("uploadFileDataHtml", uploadFileDataHtml);
		listMap.put("feedBackHtml", feedBackHtml);
		listMap.put("changeMaterialHtml", changeMaterialHtml);
		listMap.put("bigcargoStyle", bigStyleObj);
		listMap.put("styleSizeList", styleSizeList);
		return renderString(response, listMap);
	}

	/**
	 * @Title: 新建编辑保存
	 * @Description: 检索
	 * @param bigcargoStyle
	 * @param model
	 * @return url
	 */
	@RequiresPermissions("specimen:demand:edit")
	@RequestMapping(value = "saveData")
	@ResponseBody
	public String saveData(BigcargoStyle bigcargoStyle, Model model, HttpServletRequest request,
			HttpServletResponse response) throws ResourceException {
		try {

			bigcargoStyle.setPhaseCd(ResourcesUtil.getConfig("audit_phase_specimen"));
			if ("1".equals(bigcargoStyle.getUpOrCreateflg())) {
				int count = bigcargoStyleService.countRequestId(bigcargoStyle);
				String strCount = "";
				if (count < 10) {
					strCount = "0" + count;
				} else {
					strCount = count + "";
				}
				bigcargoStyle.setSampleRequestNo("10" + strCount + bigcargoStyle.getStyleNo());
				bigcargoStyleService.insertStyleSampleDemand(bigcargoStyle);
			} else {
				// bigcargoStyle.setSampleRequestNo("10" + bigcargoStyle.getStyleNo());
				bigcargoStyleService.updateStyleSampleDemand(bigcargoStyle);
			}

		} catch (SQLException e) {
			// 返回提示信息
			return renderString(response, AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		}
		// ajax返回结果
		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName("warehouse_edit_save_msg_success")));

	}

	/**
	 * @Title: 样板文件画面迁移
	 * @Description: 下拉列表生成
	 * @param bigcargoStyle
	 * @param model
	 * @return url
	 */
	@RequiresPermissions("specimen:demand:view")
	@RequestMapping(value = { "uploadFileMaterial" })
	public String uploadFileMaterial(BigcargoStyle bigcargoStyle, Model model) {
		// 物料类别
		List<Dict> materialList = DictUtils.getDictList(ResourcesUtil.getConfig("categoryCD"));
		model.addAttribute("materialList", materialList);
		String flg = bigcargoStyle.getUploadFlg();

		if ("5".equals(flg)) {
			model.addAttribute("pageFlg", (Integer.parseInt(flg) - 1) + "");
		} else if ("6".equals(flg)) {
			model.addAttribute("pageFlg", (Integer.parseInt(flg) - 1) + "");
		}
		// 创建人员
		model.addAttribute("user", UserUtils.getUser());
		return "modules/order/uploadFileMaterial";
	}

	/**
	 * @Title: 样板文件画面迁移
	 * @Description: 下拉列表生成
	 * @param bigcargoStyle
	 * @param model
	 * @return url
	 */
	@RequiresPermissions("specimen:demand:view")
	@RequestMapping(value = { "styleSizeList" })
	public String styleSizeList(BigcargoStyle bigcargoStyle, Model model) {
		bigcargoStyle.setPhaseCd(ResourcesUtil.getConfig("audit_phase_style"));
		BigcargoStyle objBigStyleList = bigcargoStyleService.styleSizeFitList(bigcargoStyle);
		model.addAttribute("StyleOptionList", objBigStyleList.getBigcargoStyleFitProperty().getBigcargoStyleFitProperty());
		model.addAttribute("styleFit", objBigStyleList.getSampleTypeDataList().getStyleFit().getStyleFitList());
		model.addAttribute("styleSizeList", objBigStyleList.getSampleTypeDataList().getSampleTypeList());
		model.addAttribute("operatingList", objBigStyleList.getProduceParameter().getProduceParameterList());
		return "modules/order/specimenDemandCreate";
	}

	/**
	 * @Title: 生成HTML
	 * @return HTML
	 */
	public String createHtml(Map<String, Object> map, String fileName) {
		String tempHtml = "";
		try {
			tempHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(fileName), map);
		} catch (Exception e) {
			return tempHtml;
		}
		return tempHtml;
	}

	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("specimen:demand:view")
	@RequestMapping(value = { "selectEmployeeImage" })
	public String selectEmployeeImage(SampleEmployeeEntity sampleEmployeeEntity) {
		return "modules/order/specimenSelectEmployee";
	}

	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("specimen:demand:view")
	@RequestMapping(value = { "selectEmployee" })
	public String selectEmployee(SampleEmployeeEntity sampleEmployeeEntity, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "sampleEmployee");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&employeeName=");
		searchParam.append(sampleEmployeeEntity.getEmployeeName());
		List<SampleEmployeeEntity> sampleEmployeeList = specimenDemandService.findSampleEmployee(sampleEmployeeEntity);
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		try {
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("sampleEmployees", sampleEmployeeList);
			strHtml = FreeMarkerTemplateUtils
					.processTemplateIntoString(freemarkerConfiguration.getTemplate("sampleEmployee.ftl"), map);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
		}

		listMap.put("sampleEmployee", strHtml);
		// ajax返回结果
		return renderString(response, listMap);
	}
}
